package com.efuture.netrequestdemo.buiness

import com.efuture.netrequestdemo.bean.Project
import com.efuture.netrequestdemo.bean.User
import com.efuture.netrequestdemo.network.ApiParameter
import com.efuture.netrequestdemo.network.NetService
import com.efuture.netrequestdemo.utils.ToastUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**

 *@description:用户业务处理类
 * @author: zhaoshanshan
 * @date: 2022/3/26 11:04 上午

 */
class UserBuiness {

    private object Holder {  // 单例
        val INSTANCE = UserBuiness()
    }
    companion object { // 派生
        val instance = Holder.INSTANCE
    }

    //用户注册
    fun userRegister(mainScope: CoroutineScope){
        val userName = "zhaoshanshna1"
        val password = "123456"
        val repassword= password
        mainScope.launch(Dispatchers.Main) {
            //注册
            var user: User? = NetService.request(ApiParameter.registerUser(userName,password,repassword))
            if(null!=user&&user.errorCode==0){
                ToastUtils.showShort(user.data.nickname)
            }else{
                if(null!=user){
                    ToastUtils.showShort(user.errorMsg)
                    userlogin(mainScope,userName,password)
                }else{
                    ToastUtils.showShort("返回为null")
                }
            }
        }
    }

    //用户登录
    fun userlogin(mainScope: CoroutineScope,userName:String,password:String){
        mainScope.launch(Dispatchers.Main) {
            //登录
            val loginUser: User? = NetService.request(ApiParameter.loginUser(userName,password))
            if(null!=loginUser&&loginUser.errorCode==0){
                ToastUtils.showShort("登录成功")
            }else{
                ToastUtils.showShort("登录失败")
            }
        }
    }

    //获取项目资源

    fun getProjectData(mainScope: CoroutineScope){
        mainScope.launch(Dispatchers.Main) {
            val cid = "294"
            val projectData: Project? = NetService.request(ApiParameter.getProject(cid))
            if (null != projectData && projectData.errorCode == 0) {
                ToastUtils.showShort(projectData.data.datas[0].chapterName)
            } else {
                ToastUtils.showShort("获取文章列表数据失败")
            }
        }
    }
}